package com.evola.rm.view.project
{
	import com.evola.rm.model.Alias;
	import com.evola.rm.model.Language;
	import com.evola.rm.model.Project;
	import com.evola.rm.model.ResourceItem;
	import com.evola.rm.model.ResourceKey;
	import com.evola.rm.utils.FilterUtils;
	import com.evola.rm.utils.StringUtils;
	import com.evola.rm.view.project.tree.ResourceKeyTreeItem;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import mx.collections.ArrayCollection;
	import mx.collections.ListCollectionView;
	import mx.collections.Sort;
	import mx.controls.Alert;
	import mx.utils.ObjectUtil;
	import mx.utils.StringUtil;

	[Bindable]
	public class ProjectModel
	{

		public var project:Project;
		public var resourceKeysRoot:ResourceKeyTreeItem;
		public var resourceKeys:ArrayCollection;
		public var selectedLanguage:Language;
		public var numOfKeys:int=0;
		public var projectUpdated:Boolean;
		public var projectFile:File;
		public var searchText:String="";
		public var filterMissingKeys:Boolean=false;
		public var selectedKey:ResourceKey;
		public var isInsertMode:Boolean;
		public var searchAlias:Alias;

		public function ProjectModel()
		{
		}

		public function setup(project:Project, file:File):void
		{

			this.project=project;
			this.projectUpdated=false;
			this.projectFile=file;

			createResourceItems();
		}

		private function createResourceItems():void
		{

			var startTime:Number=new Date().time;

			try
			{


				//usput pravimo listu svih kljuceva
				var rootKey:ResourceKeyTreeItem=new ResourceKeyTreeItem();
				rootKey.expression="";
				rootKey.children=new ArrayCollection();

				var keys:ArrayCollection=new ArrayCollection();

				var count:int=0;

				var hash:Object={};

				var file:File;
				var stream:FileStream;
				var fileData:String;
				var rows:Array;
				var lastComment:String;
				var item:ResourceItem;
				var currentPath:String;
				var currentItem:ResourceKeyTreeItem;
				var part:String;
				var treeItem:ResourceKeyTreeItem;

				//sada treba da napravimo sve resource item-e a to radimo
				//tako sto pravimo set svih itema iz svih dostupnih jezika
				for each (var language:Language in project.languages)
				{

					language.items=new ArrayCollection();
					language.itemsHash={};

					file=new File(language.path);
					stream=new FileStream();
					stream.open(file, FileMode.READ);

					fileData=stream.readUTFBytes(stream.bytesAvailable);

					rows=fileData.split("\n");

					lastComment="";

					for each (var row:String in rows)
					{

						row=StringUtils.trimLeft(row);

						//ako je prazan red u pitanju njega ignorisemo
						if (!row)
							continue;

						if (row.indexOf("#") == 0)
						{

							if (lastComment != "")
								lastComment=lastComment + "\n";

							lastComment+=row;
						}
						else
						{

							item=ResourceItem.create(row, lastComment, this);
							language.items.addItem(item);
							language.itemsHash[item.key.expression]=item;

							//sada resetujemo vrednost komentara
							lastComment="";

							if (hash.hasOwnProperty(item.key.expression))
							{

								//vec imamo ovaj kljuc
								continue;
							}

							hash[item.key.expression]=1;

							keys.addItem(item.key.copy());

							//sada algoritam za pravljenje stabla
							currentPath="";
							currentItem=rootKey;

							count++;

//							for (var i:int=0; i < item.key.chain.length; i++)
//							{
//
//								part=item.key.chain[i];
//
//								if (currentPath != "")
//									currentPath=currentPath + ".";
//
//								currentPath=currentPath + part;
//
//								treeItem=currentItem.getItem(currentPath);
//
//								if (!treeItem)
//								{
//
//									treeItem=new ResourceKeyTreeItem();
//									treeItem.expression=currentPath;
//									treeItem.children=new ArrayCollection();
//									treeItem.projectModel=this;
//
//									currentItem.children.addItem(treeItem);
//								}
//
//								currentItem=treeItem;
//							}
						}
					}
				}

				var endTime:Number=new Date().time;

				trace("TREE BUILDING TIME: " + (endTime - startTime) + "ms");

//				resourceKeysRoot=rootKey;
				numOfKeys=count;

				keys.filterFunction=filterFunction;

				//pravimo i sort
				var sort:Sort=new Sort();
				sort.compareFunction=function(item1:ResourceKey, item2:ResourceKey, fields:Array=null):int
				{

					return ObjectUtil.compare(item1.expression, item2.expression);
				};
				
				keys.sort = sort;
				
				keys.refresh();
				resourceKeys = keys;

				if (project.languages.length > 0)
					selectedLanguage=project.languages.getItemAt(0) as Language;

			}
			catch (e:Error)
			{

				Alert.show(e.message);
			}
		}

		private function filterFunction(item:ResourceKey):Boolean
		{
			return FilterUtils.listFilterFunction(item, this);
		}

		public function getResourceKey(expression:String):ResourceKey
		{

			for each (var key:ResourceKey in resourceKeys)
			{

				if (key.expression == expression)
					return key;
			}

			return null;
		}

	}
}
